package utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import task_system.TaskSystem;

public class FileHelper {
	private static FileHelper instance;
	
	public static FileHelper getInstance(){
		if(instance == null)
			instance = new FileHelper();
		
		return instance;
	}
	
	protected FileHelper(){

	}
	
	public TaskSystem extract_system(String fileName) throws IOException{
		File file = new File("Tasks/" + fileName);
		FileInputStream fis = new FileInputStream(file);
		ArrayList<Character> task_elem = new ArrayList<Character>();
		ArrayList<int[]> task_system = new ArrayList<int[]>();
		int n = 0; 
		char c;
		while ((n = fis.read()) != -1){ 
			c = (char)n;
			switch(c){
				case '\n':
					break;
				case ' ' : 
					break;
				default :  task_elem.add(c);
					if(task_elem.size() == 3){
						task_system.add(new int[]{Character.getNumericValue(task_elem.get(0)), 
													Character.getNumericValue(task_elem.get(1)),
													Character.getNumericValue(task_elem.get(2))});
						task_elem.clear();
					}
					break;
			}	
		}

		fis.close();
		
		return new TaskSystem(task_system);
	}
	
	public ArrayList<String> all_system_paths() throws IOException{
		File folder = new File("Tasks");
		File[] list_of_files = folder.listFiles();
		
		Pattern p = Pattern.compile(".*set[0-9]*");
		
		ArrayList<String> paths = new ArrayList<String>();
		
		for(File f : list_of_files){
			Matcher m = p.matcher(f.getAbsolutePath());
			if(m.matches())
				paths.add(f.getAbsolutePath());
		}
		return paths;
	}
	
	public void writeFile(String text, String fileName) throws IOException{
		System.out.println("writing " + fileName );
		FileWriter fstream = new FileWriter("Results/"+fileName);
		BufferedWriter out = new BufferedWriter(fstream);
		out.write(text);
		out.close();
		System.out.println("writing output done");
		
	}
}
